package com.ziq.zcamp.wxapi

import android.content.Intent
import android.os.Bundle
import android.view.Window
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.ziq.zcamp.manager.GlobalContextManager
import com.ziq.zcamp.manager.WXAccount

class WXEntryActivity : AppCompatActivity(), IWXAPIEventHandler {

    private lateinit var api: IWXAPI

    override fun onCreate(savedInstanceState: Bundle?) {
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        super.onCreate(savedInstanceState)
        api = WXAPIFactory.createWXAPI(
            GlobalContextManager.appContext,
            WXAccount.APP_ID,
            true
        ) // 初始化微信API
        api.registerApp(WXAccount.APP_ID) // 注册微信
        api.handleIntent(intent, this)
        finish()
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
        api.handleIntent(intent, this)
    }

    override fun onReq(p0: BaseReq?) {
    }

    override fun onResp(resp: BaseResp?) {
        when (resp!!.type) {
            ConstantsAPI.COMMAND_PAY_BY_WX -> {
                finish()
            }
            ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX, ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX -> finish()
            ConstantsAPI.COMMAND_SENDAUTH -> {
                when (resp.errCode) {
                    BaseResp.ErrCode.ERR_OK -> {
                        val extras = Bundle()
                        resp.toBundle(extras)
//                        EventBus.getDefault().post(LoginEvent(LoginEvent.GET_WEIXIN_CODE, extras))
                    }
                    BaseResp.ErrCode.ERR_AUTH_DENIED,
                    BaseResp.ErrCode.ERR_SENT_FAILED,
                    BaseResp.ErrCode.ERR_UNSUPPORT,
                    BaseResp.ErrCode.ERR_USER_CANCEL,
                    BaseResp.ErrCode.ERR_COMM ->  {// 登录失败
//                        EventBus.getDefault().post(LoginEvent(LoginEvent.GET_WEIXIN_CODE, null))
                    }
                    else -> {
                    }
                }
                sendTrackThreePartyLoginResult(resp.errCode)
            }
            else -> {
                if(resp.errCode != BaseResp.ErrCode.ERR_OK && resp.errStr != null && resp.errStr.isNotEmpty()){
                    Toast.makeText(GlobalContextManager.appContext, "${resp.errStr}", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }


    private fun sendTrackThreePartyLoginResult(errcode : Int){
    }

}